package com.rainbow.utils;

public class IsChineseUtil {

    /**
     * 是否是中文字符
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 保留前len或者len+1个字符，中文算两个字符
     *
     * @param str
     * @param len
     * @return
     */
    public static String preserve(String str, int len) {
        if (len < 0 || str == null) {
            return str;
        }
        int curLen = 0, index = 0;
        String result = "";
        while (index < str.length() && curLen < len) {
            result += str.charAt(index);
            curLen += isChinese(str.charAt(index++)) ? 2 : 1;
        }
        result += index >= str.length() ? "" : "...";
        return result;
    }

    public static void main(String[] args) {
        System.out.println(IsChineseUtil.preserve("旺旺旺旺旺财旺运气旺怎么都旺", 12));
        System.out.println(IsChineseUtil.preserve("旺旺旺旺旺财", 12));
        System.out.println(IsChineseUtil.preserve("旺旺旺旺", 12));
        System.out.println(IsChineseUtil.preserve("abcaaas张伟龙", 12));
    }
    
    public static boolean isAllChinese(String arg){
		if(arg==null){
			return false;
		}
//		String reg = "[\\u4e00-\\u9fa5]+";
		String reg = "^[\\u4e00-\\u9fa5]+(·[\\u4e00-\\u9fa5]+)*$";
	    return arg.matches(reg);
	}
    
    /**
     * ("123456789",3,3)
     * result:
     * 123***789
     */
	public static String getSecretData(String source,Integer pre,Integer after){
		if(source==null||source.length()==0){
			return "";
		}
		Integer length = source.length();
		StringBuilder dest = new StringBuilder();
		String preStr = "";
		String afterStr = "";
		if(pre!=null&&length>pre){
			preStr = source.substring(0,pre);//前三位	
		}
		if(after!=null&&length>after){
			afterStr = source.substring(length-after);//后四位
		}
		pre = pre==null?0:pre;
		after = after==null?0:after;
		Integer rest = length-pre-after;
		if(rest<=0){
			rest = length;
		}
		dest.append(preStr);
		for(int i=0;i<rest;i++){
			dest.append("*");
		}
		dest.append(afterStr);
		
		return dest.toString();
	}
}
